package com.tanhua.admin.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;

import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisMapper analysisMapper;




    /**
     * 完成数据统计
     *   从tb_log表中统计数据，保存或者更新到tb_analysis
     *   判断依据 ： record_date
     */
    public void analysis() throws ParseException {
        //1、获取时间
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); //2021-08-03
        String yestodayStr =  DateUtil.yesterday().toString("yyyy-MM-dd"); //工具类
        //2、调用logMapper查询所需要的统计数据
        Integer numRegistered = logMapper.queryByTypeAndLogTime("0102",todayStr);
        Integer numLogin = logMapper.queryByTypeAndLogTime("0101",todayStr);
        Integer numActive = logMapper.queryByLogTime(todayStr);
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr,yestodayStr);
        //3、根据record_date查询统计表中是否有今日的统计数据
        Date recordDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
        QueryWrapper<Analysis> qw = new QueryWrapper<Analysis>();
        qw.eq("record_date",recordDate);
        Analysis analysis = analysisMapper.selectOne(qw);
        //判断是否存在
        if(analysis != null) {
            //3.1 如果数据存在（更新）
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumLogin(numLogin);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysisMapper.updateById(analysis);
        }else {
            //3.2 数据不存在（保存）
            analysis = new Analysis();
            analysis.setNumRetention1d(numRetention1d);
            analysis.setNumLogin(numLogin);
            analysis.setNumRegistered(numRegistered);
            analysis.setNumActive(numActive);
            analysis.setRecordDate(recordDate);
            analysis.setCreated(new Date());
            analysisMapper.insert(analysis);
        }
    }

}
